package com.kjc.demo.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

public class WSServerInitialzer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // websocket 基于http协议，所以要有http编解码器
        pipeline.addLast(new HttpServerCodec());
        // 对写大数据流的支持
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(1024*64));
        // 如果是读空闲或者写空闲，不处理
        pipeline.addLast(new IdleStateHandler(8, 10, 12));
        // webSocket 数据压缩扩展，当添加这个的时候WebSocketServerProtocolHandler的第三个参数需要设置成true
//        pipeline.addLast(new WebSocketServerCompressionHandler());
        // 聚合 websocket 的数据帧，因为客户端可能分段向服务器端发送数据
        // https://github.com/netty/netty/issues/1112 https://github.com/netty/netty/pull/1207
//        pipeline.addLast(new WebSocketFrameAggregator(10 * 1024 * 1024));
        // 路由 ws 为客户端访问路径
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        // 自定义的handler
        pipeline.addLast(new WsHandler());
//        // 自定义处理器 - 处理 web socket 文本消息
//        .addLast(new TextWebSocketHandler())
//        // 自定义处理器 - 处理 web socket 二进制消息
//        .addLast(new BinaryWebSocketFrameHandler());
    }

}
